package com.linkdood.app.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkdood.app.constants.ErrorCode;
import com.linkdood.app.domain.ThirdParty;
import com.linkdood.app.exception.GeneralException;
import com.linkdood.app.exception.InvalidParamException;
import com.linkdood.app.mapper.ThirdPartyMapper;
import com.linkdood.app.service.ThirdPartyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 第三方平台 Service
 *
 * @author hycao
 */
@Slf4j
@Service
public class ThirdPartyServiceImpl extends ServiceImpl<ThirdPartyMapper, ThirdParty> implements ThirdPartyService {

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public ThirdParty getThirdParty(String thirdPartyId) {
        log.debug("getThirdParty() : id={}", thirdPartyId);
        Optional<ThirdParty> thirdParty = lambdaQuery().eq(ThirdParty::getId, thirdPartyId).oneOpt();
        if (!thirdParty.isPresent()) {
            throw new InvalidParamException("thirdPartyId");
        }
        return thirdParty.get();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "accessToken", key = "#thirdParty.getAppId()")
    @Override
    public void updateThirdParty(ThirdParty thirdParty) {
        if (StringUtils.isEmpty(thirdParty.getId())) {
            throw new InvalidParamException("ThirdPartyId");
        }
        lambdaUpdate().update(thirdParty);
    }

    /**
     * 获取默认第三方应用
     */
    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public ThirdParty getDefaultThirdParty() {
        Optional<ThirdParty> thirdParty = lambdaQuery().oneOpt();
        if (!thirdParty.isPresent()) {
            throw new GeneralException(ErrorCode.ERROR_NO_THIRD_PARTY);
        }
        return thirdParty.get();
    }

    /**
     * 获取具体的第三方应用
     */
    @Override
    public List<ThirdParty> listByThirdsType(Integer type) {
        return lambdaQuery().eq(ThirdParty::getType, type).list();
    }

    @Override
    public List<ThirdParty> listThirdPartyByThirdPartyId(String thirdPartyId) {
        return lambdaQuery().eq(StringUtils.isNotBlank(thirdPartyId), ThirdParty::getId, thirdPartyId).list();
    }
}
